package com.cszy.yydqbfq.common

import kotlinx.coroutines.CoroutineScope

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//全局定时器
object GlobalTimer {
    private var timerJob: Job? = null
    private var isPaused = false


    fun start(intervalMillis: Long, action: () -> Unit) {
        stop()
        timerJob = CoroutineScope(Dispatchers.Default).launch {
            while (isActive) {
                if (!isPaused) {
                    delay(intervalMillis)
                    withContext(Dispatchers.Main) {
                        action()
                    }
                } else {
                    delay(100) // 降低暂停时的CPU消耗
                }
            }
        }
    }

    fun pause() {
        isPaused = true
    }

    fun resume() {
        isPaused = false
    }

    fun stop() {
        timerJob?.cancel()
        timerJob = null
        isPaused = false
    }
}